package com.sfj.system.service.userinfo;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sfj.system.dto.LoginResDTO;
import com.sfj.system.dto.userinfo.UserInfoQueryDTO;
import com.sfj.system.dto.userinfo.UserTaskDTO;
import com.sfj.system.entity.UserInfoEntity;
import com.sfj.system.enums.DeptEnum;
import com.sfj.system.mapper.UserInfoMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author kaka
 * @date 2020-09-24
 */
@Service
public class UserInfoQueryService {

    @Resource
    private UserInfoMapper userinfoMapper;

    @Transactional(readOnly = true)
    public UserInfoEntity getById(Integer id) {
        UserInfoEntity userInfoEntity = userinfoMapper.selectByPrimaryKey(id);
        return userInfoEntity;
    }

    public IPage<UserInfoEntity> queryUserInfoList(UserInfoQueryDTO queryReq) {

        Page<UserInfoEntity> page =
                new Page<>(queryReq.getPageNo(), queryReq.getPageSize());
        return userinfoMapper.queryUserInfoList(page, queryReq);
    }

    public UserInfoEntity selectByPoliceNum(String userName) {
        return userinfoMapper.selectByPoliceNum(userName);
    }

    public LoginResDTO selectByUserName(String userName) {
        return userinfoMapper.selectByUserName(userName);
    }

    public Map<Integer, List<UserTaskDTO>> queryUserByTask(List<Integer>  levelList){
        List<UserTaskDTO> userTaskDTOS = getUserTaskList(levelList);
        final Map<Integer, List<UserTaskDTO>> groupMap =
                userTaskDTOS.stream()
                        .filter(dto -> dto.getGroupId() != null)
                        .peek(dto -> dto.setDeptName(DeptEnum.getNameById(dto.getDeptId())))
                        .collect(Collectors.groupingBy(UserTaskDTO::getGroupId));
        return groupMap;
    }

    private List<UserTaskDTO> getUserTaskList(List<Integer>  levelList){
        return userinfoMapper.queryUserByTask(levelList);
    }

    public List<Map<Integer, String>> getUserNameByIds(List<Integer> userIds) {
        return userinfoMapper.getUserNameByIds(userIds);
    }
}